export const DBUser = {
  getUserList() {
    let userList = [];
    try {
      userList = JSON.parse(window.localStorage.getItem("userList")) || [];
    } catch (error) {
      userList = [];
    }
    return userList;
  },
  setUserList(userList) {
    window.localStorage.setItem("userList", JSON.stringify(userList));
  },
  addUser(user) {
    const userList = this.getUserList();
    userList.push(user);
    this.setUserList(userList);
  },
  findUser({ userName = "", password = "" }) {
    const userList = this.getUserList();
    return userList.find(u => {
      return u.userName === userName && u.password === password;
    });
  },
  login(user) {
    window.sessionStorage.setItem("currUser", JSON.stringify(user));
  },
  getCurrUser() {
    try {
      return JSON.parse(window.sessionStorage.getItem("currUser")) || {};
    } catch (error) {
      return {};
    }
  },
  loginOut() {
    window.sessionStorage.setItem("currUser", "");
  }
};

export const DBTodo = {
  getList() {
    let todoList = [];
    try {
      todoList = JSON.parse(window.localStorage.getItem("todoList")) || [];
    } catch (error) {
      todoList = [];
    }
    return todoList;
  },
  setList(todoList) {
    window.localStorage.setItem("todoList", JSON.stringify(todoList));
  },
  addTodo(todo) {
    const todoList = this.getList();
    todoList.push(todo);
    this.setList(todoList);
  },
  delTodo(id) {
    let todoList = this.getList();
    todoList = todoList.filter(todo => todo.id !== id);
    this.setList(todoList);
  },
  todoSuccess(id) {
    let todoList = this.getList();
    todoList = todoList.map(todo => {
      if (todo.id === id) {
        todo.type = 1;
      }
      return todo;
    });
    this.setList(todoList);
  },
  todoNot(id) {
    let todoList = this.getList();
    todoList = todoList.map(todo => {
      if (todo.id === id) {
        todo.type = 0;
      }
      return todo;
    });
    this.setList(todoList);
  },
  getTodo(id) {
    const todoList = this.getList();
    return todoList.find(todo => {
      return todo.id === id;
    });
  },
  updateTodo(todo) {
    const todoList = this.getList();
    todoList.map(t => {
      if (t.id === todo.id) {
        t = Object.assign(t, todo);
      }
      return t;
    });
    this.setList(todoList);
  }
};
